package com.ygxsk.carhome.ui.leads;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.jakewharton.rxbinding4.widget.RxTextView;
import com.jakewharton.rxbinding4.widget.TextViewAfterTextChangeEvent;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.greendao.CarBrandLargeCategoryDaoManager;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.CarBrandLargeCategory;
import com.ygxsk.carhome.response.FileCarInfoAddSubmit;
import com.ygxsk.carhome.rxbus.RxBusCarBrand;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.ClearEditText;
import com.ygxsk.carhome.views.MyLinearLayoutManager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-12  10:41
 * @Description:车辆品牌的弹窗适配器
 */
public class LeadsCarBrandLargeCategorySelectPopu extends BottomPopupView {

    public LeadsCarBrandLargeCategorySelectPopu(@NonNull Context context) {
        super(context);
    }

    //因为通用界面，标志从哪个页面过来；
    private int extra_jumpfrom_where;

    private ArrayList<CarBrandLargeCategory> carBrandLargeCategory_list_outSide = new ArrayList<>();

    //对于客户的跟进状态的适配器;
    private CarBrandInfoAdapter carBrandInfoAdapter;

    //该条目的品牌弹窗，引起的弹窗，做记录，回传给主列表页面；
    private FileCarInfoAddSubmit fileCarInfoAddSubmit_current;

    //弹窗的标题
    private String titleName;

    public void setTitleName(String _titleName) {
        titleName = _titleName;
    }


    public LeadsCarBrandLargeCategorySelectPopu(@NonNull Context context, int _extra_action, ArrayList<CarBrandLargeCategory> _carBrandLargeCategoryList) {
        super(context);

        //不这样等于，直接 赋值 添加；
        //station_list_outSide = _stationDatas;
        extra_jumpfrom_where = _extra_action;

        if (_carBrandLargeCategoryList != null && !_carBrandLargeCategoryList.isEmpty()) {

            if (carBrandLargeCategory_list_outSide != null && !carBrandLargeCategory_list_outSide.isEmpty()) {
                carBrandLargeCategory_list_outSide.clear();
            }

            if (carBrandLargeCategory_list_outSide != null) {
                carBrandLargeCategory_list_outSide.addAll(_carBrandLargeCategoryList);
            }

        }

    }

    //携带一个条目的对象，然后给对象再回传
    public LeadsCarBrandLargeCategorySelectPopu(@NonNull Context context, int _extra_action, ArrayList<CarBrandLargeCategory> _carBrandLargeCategoryList, FileCarInfoAddSubmit _fileCarInfoAddSubmit) {
        super(context);

        //不这样等于，直接 赋值 添加；
        //station_list_outSide = _stationDatas;

        extra_jumpfrom_where = _extra_action;
        fileCarInfoAddSubmit_current = _fileCarInfoAddSubmit;

        if (_carBrandLargeCategoryList != null && !_carBrandLargeCategoryList.isEmpty()) {

            if (carBrandLargeCategory_list_outSide != null && !carBrandLargeCategory_list_outSide.isEmpty()) {
                carBrandLargeCategory_list_outSide.clear();
            }

            if (carBrandLargeCategory_list_outSide != null) {
                carBrandLargeCategory_list_outSide.addAll(_carBrandLargeCategoryList);
            }

        }

    }


    @Override
    protected int getImplLayoutId() {
        return R.layout.populeadscarbrand;
    }


    @Override
    protected void onCreate() {
        super.onCreate();

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "onCreate--onCreate---onCreate--onCreate--onCreate");

        //取消按钮
        TextView btn_dialog_search_cancel = (TextView) this.findViewById(R.id.btn_dialog_search_cancel);
        //确定按钮
        TextView btn_dialog_search_decide = (TextView) this.findViewById(R.id.btn_dialog_search_decide);
        //中间的标题内容
        TextView titleNameWhereMiddle = (TextView) this.findViewById(R.id.titlenamewheremiddle);
        if (titleNameWhereMiddle != null) {
            titleNameWhereMiddle.setText(titleName);
        }

        //搜索编辑框；
        ClearEditText et_searchInCustomSmall = (ClearEditText) this.findViewById(R.id.et_searchincustomsmallpo);
        //默认清除焦点
        et_searchInCustomSmall.clearFocus();

        //初始化适配器列表
        RecyclerView recyclerViewInStation = (RecyclerView) this.findViewById(R.id.recyclerviewinbrand);
        MyLinearLayoutManager myLinearLayoutManager = new MyLinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerViewInStation.setLayoutManager(myLinearLayoutManager);

        //适配器的创建；页面适配器使用的是一个条目项布局;
        carBrandInfoAdapter = new CarBrandInfoAdapter(R.layout.carbrandinfoadapter, carBrandLargeCategory_list_outSide);
        recyclerViewInStation.setAdapter(carBrandInfoAdapter);

        if (carBrandInfoAdapter != null) {
            carBrandInfoAdapter.notifyDataSetChanged();
        }

        //单独的点击条目
        carBrandInfoAdapter.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //直接设置勾选；
                CarBrandLargeCategory carBrandLargeCategory = (CarBrandLargeCategory) adapter.getItem(position);

                if (carBrandLargeCategory != null) {

                    //发送消息，给业务台账，填充选中的业务类型；
                    for (CarBrandLargeCategory itemBottom : carBrandInfoAdapter.getData()) {

                        //是唯一的；
                        if (TextUtils.equals(carBrandLargeCategory.getCarBrandId(), itemBottom.getCarBrandId())) {

                            if (itemBottom.isChecked()) {
                                itemBottom.setChecked(false);
                            } else {
                                itemBottom.setChecked(true);
                            }

                            LogUtils.json("itchen--选中的", itemBottom);

                        } else {
                            itemBottom.setChecked(false);
                        }

                    }

                    //是单选，直接刷新；
                    if (carBrandInfoAdapter != null) {
                        carBrandInfoAdapter.notifyDataSetChanged();
                    }

                }
            }
        });


        //对搜索文本监听、
        if (et_searchInCustomSmall != null) {

            et_searchInCustomSmall.clearFocus();

            //使用rxbinding做监听，如果1秒钟没有输入的话就自动清除焦点
            RxTextView.afterTextChangeEvents(et_searchInCustomSmall)
                    .debounce(ConstantApi.TIME_DELAY300, TimeUnit.MILLISECONDS)//
                    .skip(1)//过滤到第一个空字符的内容
                    .subscribeOn(AndroidSchedulers.mainThread())//
                    .observeOn(AndroidSchedulers.mainThread())//
                    .subscribe(new Consumer<TextViewAfterTextChangeEvent>() {
                        @Override
                        public void accept(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Throwable {

                            //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "监听到的内容是->" + textViewAfterTextChangeEvent.getView().getText().toString());

//                            if (et_searchInCustomSmall.isFocused()) {
//                                //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "afterTextChangeEvents--处于获取焦点状态");
//                                et_searchInCustomSmall.clearFocus();//如果处于占用焦点之中，那么清理焦点
//                            }

                            method_SearchSomeThing(textViewAfterTextChangeEvent.getView().getText().toString().trim());

                        }
                    }, new Consumer<Throwable>() {

                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            //
                        }
                    });

            //软键盘的【搜索】
            et_searchInCustomSmall.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {

                    if (actionId == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {

                        KeyboardUtils.hideSoftInput(LeadsCarBrandLargeCategorySelectPopu.this);

                        method_SearchSomeThing(et_searchInCustomSmall.getText().toString().trim());

                        return true;
                    }

                    return false;
                }
            });

        }

        //【取消】按钮
        if (btn_dialog_search_cancel != null) {
            btn_dialog_search_cancel.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }

        //【确定】按钮
        if (btn_dialog_search_decide != null) {
            btn_dialog_search_decide.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    //method_test();

                    //即将被传递的单个item;
                    CarBrandLargeCategory carBrandLargeCategory_upLoad = null;

                    if (carBrandLargeCategory_list_outSide != null && !carBrandLargeCategory_list_outSide.isEmpty()) {

                        //----------------------------------------------------------------------------------------
                        Iterator<CarBrandLargeCategory> iterator = carBrandLargeCategory_list_outSide.iterator();

                        if (iterator != null) {

                            while (iterator.hasNext()) {

                                CarBrandLargeCategory item = iterator.next();

                                if (item != null) {

                                    if (item.isChecked()) {

                                        carBrandLargeCategory_upLoad = item;

                                        LogUtils.json(ConstantSign.LOGCAT_NOMAL + "选中条目项是->", item);

                                        break;
                                    }

                                }
                            }
                        }

                        //----------------------------------------------------------------------------------------
                        if (carBrandLargeCategory_upLoad != null) {

                            if (extra_jumpfrom_where == ExtraValue.MODIFY_LEAD_CARBRAND_SELECT) {

                                //标识是从：
                                RxBusCarBrand rxBusCarBrand = new RxBusCarBrand();
                                rxBusCarBrand.setActionFlag(ExtraValue.MODIFY_LEAD_CARBRAND_SELECT);
                                rxBusCarBrand.setCarBrandLargeCategory(carBrandLargeCategory_upLoad);
                                RxBus.getInstance().post(rxBusCarBrand);

                            } else if (extra_jumpfrom_where == ExtraValue.MODIFY_ARCHIVE_FILE_ADDSUBMIT_CARBRAND_SELECT) {

                                //标识是从:档案管理的提交页面-车辆信息-用到
                                RxBusCarBrand rxBusCarBrand = new RxBusCarBrand();
                                rxBusCarBrand.setActionFlag(ExtraValue.MODIFY_ARCHIVE_FILE_ADDSUBMIT_CARBRAND_SELECT);
                                rxBusCarBrand.setCarBrandLargeCategory(carBrandLargeCategory_upLoad);
                                //2023年11月8日15:17:56 新增从主页列表携带的这条数据；
                                rxBusCarBrand.setFileCarInfoAddSubmit(fileCarInfoAddSubmit_current);
                                RxBus.getInstance().post(rxBusCarBrand);

                            }

                            //关闭该弹窗内容
                            dismiss();

                        } else {
                            //请选择 客户来源；
                            ToastUtils.showShort(R.string.select_lead_carbrand_toast);
                        }

                    } else {
                        //执行异常？
                        ToastUtils.showShort(StringUtils.getString(R.string.action_abnormal));
                    }

                }
            });
        }

    }


    private void method_SearchSomeThing(String _keyWord) {

        //获取搜索的关键字内容,刚开始默认是空值
        //String keyWord = et_searchInCustomSmall.getText().toString().trim();
        //不论有没有搜索出数据，都清空上次状态；
        //2023-6-7 10:45:18 清空上次的选中状态，防止这次选中
        method_clear_item_state();

        //如果搜索有内容，就刷新列表布局
        List<CarBrandLargeCategory> tempList = CarBrandLargeCategoryDaoManager.getInstance().queryListByKeyWord(_keyWord);

//        if (!TextUtils.isEmpty(_keyWord)) {//空的也让搜索，只是搜索出来的是全部结果；

        if (tempList != null && !tempList.isEmpty()) {

            if (carBrandLargeCategory_list_outSide != null && !carBrandLargeCategory_list_outSide.isEmpty()) {
                carBrandLargeCategory_list_outSide.clear();
            }

            if (carBrandLargeCategory_list_outSide != null) {
                carBrandLargeCategory_list_outSide.addAll(tempList);
            }

            if (carBrandInfoAdapter != null) {
                carBrandInfoAdapter.notifyDataSetChanged();
            }

        } else {

            ToastUtils.showLong(R.string.ranking_search_no_content);

//            CommUtils.checkDialog(alertViewDialogSure);
//            alertViewDialogSure = CommUtils.method_showAlertViewSingleSlowly(getContext(), ConstantSign.ALERT_TITLE, StringUtils.getString(R.string.ranking_search_no_content), true);
//            alertViewDialogSure.show();

            //如果搜索出来的是空值，最低程度给个提示；
//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "搜索是空数据-");
        }

//        }
    }

    private void method_clear_item_state() {

        if (carBrandLargeCategory_list_outSide != null && !carBrandLargeCategory_list_outSide.isEmpty()) {

            for (CarBrandLargeCategory carBrandLargeCategory : carBrandLargeCategory_list_outSide) {
                carBrandLargeCategory.setChecked(false);
            }

            if (carBrandInfoAdapter != null) {
                carBrandInfoAdapter.notifyDataSetChanged();
            }

        }

    }

    @Override
    protected void onShow() {
        super.onShow();

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "界面弹窗 弹出");

    }


    @Override
    public void onDestroy() {
        //        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "弹窗--弹窗--弹窗onDestroy--onDestroy---onDestroy--onDestroy--onDestroy");
        if (carBrandLargeCategory_list_outSide != null && !carBrandLargeCategory_list_outSide.isEmpty()) {

            for (CarBrandLargeCategory carBrandLargeCategory : carBrandLargeCategory_list_outSide) {
                carBrandLargeCategory.setChecked(false);
            }

            if (carBrandInfoAdapter != null) {
                carBrandInfoAdapter.notifyDataSetChanged();
            }

        }
        super.onDestroy();

    }

    @Override
    protected boolean onBackPressed() {
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "拦截 弹出弹窗的  返回事件");
//        CommUtils.checkDialog(alertViewDialogSure);
//        if (mDatasResources!=null&&!mDatasResources.isEmpty()){
//        }
        return super.onBackPressed();
    }

    @Override
    protected int getMaxHeight() {
        return (int) (XPopupUtils.getScreenHeight(getContext()) * .6f);
        //车辆类型 只有两个 新车或者二手车，高度不必那么高，而且是写固定的
//        return (int) (XPopupUtils.getScreenHeight(getContext()) * .3f);
    }

    /*
     * @Author:itchenqi175@163.com
     * @Time:2023-07-12  15:22
     * @Description:选择列表布局的适配器
     */
    //适配器内容：
    private class CarBrandInfoAdapter extends BaseQuickAdapter<CarBrandLargeCategory, BaseViewHolder> {

        public CarBrandInfoAdapter(int layoutResId, @Nullable List<CarBrandLargeCategory> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder baseViewHolder, CarBrandLargeCategory carBrandLargeCategory) {

            if (carBrandLargeCategory != null) {

                //是否被勾中
                boolean isChecked = carBrandLargeCategory.isChecked();
                //填充名称：
                String carBrandName = carBrandLargeCategory.getCarBrandName();
                //图片的url
                String imageUrl = carBrandLargeCategory.getLogoImg();

                //填充车辆品牌的图标
                ImageView imageViewCarInfo = (ImageView) baseViewHolder.getView(R.id.imageviewcarinfo);
                //填充名称
                TextView textViewStationNameType = (TextView) baseViewHolder.getView(R.id.textviewcarbrand);
                ImageView checkBoxInStationType = (ImageView) baseViewHolder.getView(R.id.checkboxincarbrand);

                //填充名称
                CommUtils.setText(textViewStationNameType, carBrandName);


                //加载图片
                //用户进来肯定是加载链接内的图片
                Glide.with(LeadsCarBrandLargeCategorySelectPopu.this.getContext())
                        .load(imageUrl)
                        .skipMemoryCache(true)//跳过内存缓存
                        .diskCacheStrategy(DiskCacheStrategy.NONE)//不在磁盘中缓存
                        .placeholder(R.drawable.defaulttoub)//
                        .error(R.drawable.defaulttoub)//
                        .fallback(R.drawable.defaulttoub)//
                        .centerCrop()
                        //.transition(withCrossFade())
                        .into(new CustomTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                //手动指定图片内容
                                if (imageViewCarInfo != null) {
                                    imageViewCarInfo.setImageDrawable(resource);
                                }
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {

                            }
                        });


                if (isChecked) {//表示选中
                    //字体设置为选中
//                    textViewStationNameType.setTextColor(ColorUtils.getColor(R.color.orangeygxsk));
                    textViewStationNameType.setTextColor(ColorUtils.getColor(R.color.redcomm));
                    checkBoxInStationType.setVisibility(View.VISIBLE);

//                    checkBoxInStation.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            checkBoxInStation.setVisibility(View.VISIBLE);
//                        }
//                    });

                } else {

                    textViewStationNameType.setTextColor(ColorUtils.getColor(R.color.dark));
                    checkBoxInStationType.setVisibility(INVISIBLE);

//                    checkBoxInStation.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            checkBoxInStation.setVisibility(GONE);
//                        }
//                    });

                }

            }

        }
    }

}
